﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using System.Data;

namespace BrokerBase.Lib.Tool
{
    public static class DateTimeUtil
    {
        public static DateTime ChinaStandardTime
        {
            get
            {
                DateTime dt = TimeZoneInfo.ConvertTimeToUtc(DateTime.Now, TimeZoneInfo.Local);
                dt = TimeZoneInfo.ConvertTimeFromUtc(dt, TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"));

                return dt;
            }
        }

        public static void CreatePeriodRange(int begin,int periods,ISession sess)
        {
            IDbConnection conn = sess.Connection;

            IDbTransaction tx = conn.BeginTransaction();

            IDbCommand cmd = conn.CreateCommand();
            cmd.Transaction = tx;

            string sql = "delete from Base_PeriodRange where yearperiod >= "+begin;

            try
            {

                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();

                int tmp = begin;

                for (int i = 0; i < periods; i++)
                {
                    int y = tmp / 100;
                    int m = tmp % 100;

                    DateTime dt = new DateTime(y, m, 1);

                    sql = string.Format("insert into Base_PeriodRange(YearPeriod,FYear,FPeriod) values({0},{1},{2})", tmp, y, m);

                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();

                    DateTime dt2 = dt.AddMonths(1);
                    tmp = dt2.Year * 100 + dt2.Month;

                }

                tx.Commit();
            }
            catch (Exception ex)
            {
                if (tx != null)
                    tx.Rollback();

                throw ex;
            }

        }
    }
}
